package com.lzx.tease.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.common.utils.R;
import com.lzx.tease.entity.Comments;
import com.lzx.tease.entity.SecondComments;
import com.lzx.tease.entity.vo.User;
import com.lzx.tease.feign.UserClient;
import com.lzx.tease.mapper.CommentsMapper;
import com.lzx.tease.mapper.SecondCommentsMapper;
import com.lzx.tease.service.SecondCommentsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-12-22
 */
@Service
public class SecondCommentsServiceImpl extends ServiceImpl<SecondCommentsMapper, SecondComments> implements SecondCommentsService {
    @Resource
    private SecondCommentsMapper secondCommentsMapper;

    @Resource
    private CommentsMapper commentsMapper;

    @Resource
    private UserClient userClient;

    //保存二级评论
    @Override
    public R saveSecondComments(SecondComments secondComments) {
        secondComments.setCreateTime(new Date());
        secondCommentsMapper.insert(secondComments);
        return R.ok().message("回复成功");
    }

    //获取一级和二级评论
    @Override
    public R getFirstAndSecondComments() {
        //获取一级评论
        List<Comments> commentsList = commentsMapper.selectList(null);
        //获取二级评论
        List<Comments> list = commentsList.stream().peek(comments -> {
            User user = userClient.getUserinfoByIdToOtherServe(Long.valueOf(comments.getUserId()));
            comments.setUser(user);
            QueryWrapper<SecondComments> wrapper = new QueryWrapper<>();
            wrapper.eq("first_id", comments.getId());
            List<SecondComments> secondCommentsList = secondCommentsMapper.selectList(wrapper).stream().peek(secondComments -> {
                if (secondComments.getSecondOneUserId() != -1) {
                    User secondOneUser = userClient.getUserinfoByIdToOtherServe(Long.valueOf(secondComments.getSecondOneUserId()));
                    secondComments.setSecondOneUser(secondOneUser);
                }
                User secondTwoUser = userClient.getUserinfoByIdToOtherServe(Long.valueOf(secondComments.getSecondTwoUserId()));
                secondComments.setSecondTwoUser(secondTwoUser);
            }).collect(Collectors.toList());
            comments.setSecondComments(secondCommentsList);
        }).collect(Collectors.toList());
        return R.ok().data("list", list);
    }
}
